package com.etc.sfts.controller;

import com.etc.sfts.biz.MovieBiz;
import com.etc.sfts.biz.ipml.MovieBizImpl;
import com.etc.sfts.dto.MovieAddDto;
import com.etc.sfts.dto.MovieDto;
import com.etc.sfts.dto.PageDto;
import com.etc.sfts.entity.Message;
import com.etc.sfts.entity.Movie;
import com.google.gson.Gson;
import com.sun.glass.ui.Size;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Controller
public class DoMovieController {
    @Autowired
    private MovieBiz biz;

    public MovieBiz getBiz() {
        return biz;
    }

    public void setBiz(MovieBiz biz) {
        this.biz = biz;
    }

    //获取电影总数
    @RequestMapping("/getMovieCount")
    public void getMovieCount(HttpServletResponse response) throws Exception {
        Long count = biz.getMovieCount();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(count);
        out.flush();
        out.close();

    }

    //获取按照票房排序的电影
    @RequestMapping("/getMovieOrderByajaxAndTickets")
    public void getMovieOrderByajaxAndTickets(HttpServletResponse response) throws Exception {
        List<MovieDto> list = biz.getOrderMovieByTickets();
        Gson json = new Gson();
        String str = json.toJson(list);
        System.out.println(list);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(str);
        out.flush();
        out.close();
    }

    //按照评分排序电影
    @RequestMapping("/getMovieOrderByajaxAndScore")

    public void getMovieOrderByajaxAndScore(HttpServletResponse response) throws Exception {
        List<MovieDto> list = biz.getOrderMovieByScore();
        Gson json = new Gson();
        String str = json.toJson(list);
        System.out.println(list);
        PrintWriter out = response.getWriter();
        out.print(str);
        out.flush();
        out.close();
    }

    //查询全部电影
    @RequestMapping("/getAllMovie")
    public void getAllMovie(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer page = 1;
        Integer size = 5;
        String key = "";
        try {

            if (request.getParameter("page") != null) {

                page = Integer.valueOf(request.getParameter("page"));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        try {

            if (request.getParameter("size") != null) {

                size = Integer.valueOf(request.getParameter("size"));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (request.getParameter("key") != null) {
            key = request.getParameter("key");

        }


        size = size <= 0 ? 5 : size;
        page = page <= 0 ? 1 : page;
        Long count = biz.getMovieCount();
        Integer maxPage = (int) (count % size == 0 ? (count / size) : (count / size + 1));
        page = page > maxPage ? maxPage : page;
        List<Movie> list = biz.getAllMovie((page - 1) * size, size);
        PageDto dto = new PageDto();
        dto.setKey(key);
        dto.setMaxPage(maxPage);
        dto.setOlist(list);
        dto.setPage(page);
        dto.setSize(size);
        System.out.println(list);

        Message m = new Message();
        m.setFlag(1);
        m.setMsgcontent(dto);
        Gson json = new Gson();
        String str = json.toJson(m);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(str);
        out.flush();
        out.close();
    }

    //添加电影
    @RequestMapping("/insertMovie")
    private void insertMovie(MovieAddDto dto, HttpServletResponse response, HttpServletRequest request) throws Exception {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获取当前服务器所在的磁盘地址
        String path = request.getServletContext().getRealPath("/upload");
        System.out.println("上传的地址path:" + path);
        //判断当前文件夹是否存在,不存在则创建
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //从会话中获取当前用户
        String filename = null;
        String filename3 = null;
        //获取当前上传的文件名
        filename = dto.getMovielogo().getOriginalFilename();
        filename3 = dto.getActorlogo().getOriginalFilename();
        // 对该文件进行重命名   当前系统时间毫秒数+原文件名
        filename = System.currentTimeMillis() + "-" + filename;
        filename3 = System.currentTimeMillis() + "-" + filename3;
        //获取要上传的文件的路径对象
        File file2 = new File(path + "/" + filename);
        File file3 = new File(path + "/" + filename3);

        try {
            FileUtils.copyInputStreamToFile(dto.getMovielogo().getInputStream(), file2);
            FileUtils.copyInputStreamToFile(dto.getMovielogo().getInputStream(), file3);
            System.out.println("文件上传成功！！！");
        } catch (Exception e) {
            out.print("<script>alert('保存失败，发生了异常');history.go(-1);</script>");
        }

        try {
            Movie m = new Movie();
            m.setMovie_tickets(dto.getTickets());
            m.setMovie_actors(dto.getActor());
            m.setMovie_area(dto.getArea());
            m.setMovie_duration(dto.getDuration());
            m.setMovie_info(dto.getInfo());
            m.setMovie_logo(filename);
            m.setMovie_pictures(filename3);
            m.setMovie_people(dto.getPeople());
            m.setMovie_name(dto.getName());
            m.setMovie_score(dto.getScore());
            m.setMovie_time(dto.getTime());
            m.setMovie_type(dto.getType());

            if (biz.insertMovie(m)) {

                out.print("<script>alert('保存成功');location.href='movieList.jsp';</script>");
            } else {
                out.print("<script>alert('保存失败');history.go(-1);</script>");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("<script>alert('保存失败，发生了异常');history.go(-1);</script>");
        }
        out.flush();
        out.close();


    }

    @RequestMapping("/deleteMovieByMovieId")
    public void deleteMovieByMovieId(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String mid = request.getParameter("movieid");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        try {
            Integer id = Integer.valueOf(mid);

            if (biz.deteleMovieById(id)) {
                out.print("<script>alert('删除成功！');location.href='movieList.jsp';</script>");
            } else {
                out.print("<script>alert('删除失败！');histroy.go(-1);</script>");
            }
        } catch (Exception e) {
            out.print("<script>alert('参数异常，删除失败！');histroy.back();</script>");
        }
        out.flush();
        out.close();

    }
    //导出excel文件
    @RequestMapping("/exportExcel")
    @ResponseBody
    public String exportExcel(HttpServletResponse response, Map<String, Object> params) {

        HSSFWorkbook workbook = biz.exportExcel(params);
        try {
            if (response != null) {
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=\"" + new String(("电影信息" + ".xls").getBytes("gb2312"), "ISO8859-1"));
                OutputStream out = response.getOutputStream();
                workbook.write(out);
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

